//arrayBuffer转16进制字符串
function bufferToHex(buffer) {
	const hexArr = Array.prototype.map.call(
		new Uint8Array(buffer),
		function(bit) {
			return ('00' + bit.toString(16)).slice(-2)
		}
	)
	return hexArr.join('');
}

//弹出提示
const msg = (title, icon = 'none', mask = false, duration = 2000) => {
	//统一提示方便全局修改
	if (Boolean(title) === false) {
		return;
	}
	uni.showToast({
		title,
		duration,
		mask,
		icon
	});
	setTimeout(function() {
		uni.hideToast();
	}, duration);
}

//确认框
function confirm(content, success, title = '') {
	uni.showModal({
		title: title,
		content: content,
		success: function(res) {
			if (res.confirm) {
				success();
			}
		},
	});
}

//处理异常结果
function ErrorCode(obj, source) {
	var language = uni.getStorageSync('language');
	if (obj) {
		var code = obj.code;
		var message = obj.message;
		switch (code) {
			case -1:
				msg(language.b1);
				break;
			case 0:
				break;
			case 10000:
				msg(language.b2);
				break;
			case 10001:
				msg(language.b3);
				break;
			case 10002:
				msg(language.b4);
				break;
			case 10003:
				msg(language.b5);
				break;
			case 10004:
				msg(language.b6);
				break;
			case 10005:
				msg(language.b7);
				break;
			case 10006:
				msg(language.b8);
				break;
			case 10007:
				msg(language.b9);
				break;
			case 10009:
				msg(language.b10);
				break;
			case 10012:
				msg(language.b11);
				break;
			default:
				msg(language.b12 + code);
				console.log('未处理的错误', obj);
				break;
		}
	}
}

var bleCallBack = {
	CharacteristicValueChange: function(res) {
		console.log('未设置数据修改回调函数！');
	},
	ConnectionStateChange: function(res) {
		console.log('未设置状态修改回调函数！');
	},
	notifyBLE: function() {
		console.log('未设置通知功能回调函数！');
	}
};

//初始化蓝牙
function Init(callback) {
	uni.openBluetoothAdapter({
		success: function(res) {
			console.log('Init().openBluetoothAdapter', res);
			if (res.errno == 0 || res.errCode == 0) {
				//开启监听连接状态
				uni.onBLEConnectionStateChange(function(event) {
					if (event) {
						var deviceId = event.deviceId;
						var connected = event.connected;
						getApp().globalData.bleObj.state = connected;
						if (connected) {
							getApp().globalData.bleObj.deviceId = deviceId;
							uni.setStorageSync('deviceId', deviceId);
							const version = getApp().globalData.bleVersion
							if (version <= 1 || version * 1 === 3) {
								uni.setBLEMTU({
									deviceId: deviceId,
									mtu: 246
								})
							}
						} else {
							uni.showToast({
								icon:"none",
								title: '蓝牙已断开连接'
							})
							getApp().globalData.bleObj.deviceId = '';
						}
						bleCallBack.ConnectionStateChange(event);
					}else{
						bleCallBack.ConnectionStateChange({});
					}
				});
				//监听低功耗蓝牙设备的特征值变化事件
				uni.onBLECharacteristicValueChange(function(event) {
					if (event) {
						var deviceId = event.deviceId;
						var serviceId = event.serviceId;
						var characteristicId = event.characteristicId;
						var value = event.value;
						var Hex = bufferToHex(value);
						// console.log("接受到的数据：" + Hex);
						var appDeviceId = getApp().globalData.bleObj.deviceId;
						var appServiceId = getApp().globalData.bleObj.serviceId;
						var appCharacteristicId = getApp().globalData.bleObj.notifyBLE;
						if (deviceId == appDeviceId && serviceId == appServiceId &&
							characteristicId == appCharacteristicId) {
							bleCallBack.CharacteristicValueChange(Hex.toUpperCase());
						}
					}
				});
				if (callback) {
					callback();
				}
			} else {
				ErrorCode(res, '蓝牙初始化success');
			}
		},
		fail: function(res) {
			ErrorCode(res, '蓝牙初始化fail');
		}
	});
}

function notifyBLECharacteristicValueChange(deviceId, serviceId, characteristicId, callback) {
	uni.notifyBLECharacteristicValueChange({
		deviceId: deviceId,
		serviceId: serviceId,
		characteristicId: characteristicId,
		state: true,
		success: function(e) {
			if (e.errCode == 0 || e.errno == 0) {
				setTimeout(function() {
					getApp().globalData.bleObj.state = true;
					getApp().globalData.bleObj.isNotify = true;
					uni.hideLoading();
					if (callback) {
						callback();
					}
					if (bleCallBack.notifyBLE) {
						bleCallBack.notifyBLE();
					}
				}, 1000);
			} else {
				ErrorCode(e,
					'启用notify功能success'
				);
			}
		},
		fail: function(e) {
			ErrorCode(e,
				'启用notify功能fail');
		}
	});
}

function getBLEDeviceCharacteristics(deviceId, serviceId, callback) {
	uni.getBLEDeviceCharacteristics({
		deviceId: deviceId, // 蓝牙设备id
		serviceId: serviceId, // 蓝牙服务UUID
		success(characteristics) {
			const bleVersion = getApp().globalData.bleVersion
			
			if(!characteristics.characteristics||characteristics.characteristics.length<1){
				return
			}
			
			//console.log('getBLEDeviceCharacteristics', characteristics);
			let characteristicsId = characteristics.characteristics[0].uuid
			if (bleVersion * 1 === 1) {
				characteristicsId = characteristics.characteristics[1].uuid
			}
			getApp().globalData.bleObj.characteristicId = characteristicsId
			if (bleVersion * 1 === 3) {
				characteristicsId = characteristics.characteristics[0].uuid
				getApp().globalData.bleObj.characteristicId = characteristics.characteristics[1].uuid
			}
			getApp().globalData.bleObj.notifyBLE = characteristicsId
			notifyBLECharacteristicValueChange(deviceId, serviceId, characteristicsId,
				callback)
		}
	})
}

function getBLEDeviceServices(deviceId, callback) {
	uni.getBLEDeviceServices({
		deviceId: deviceId,
		success(res) {
			console.log('getBLEDeviceServices', res);
			const bleVersion = getApp().globalData.bleVersion
			let serviceId = undefined
			if(!res.services||res.services.length<1){
				uni.hideLoading()
				if(callback){
					callback();
				}
				return
			}
			serviceId = res.services[0].uuid
			if (bleVersion * 1 === 1) {
				serviceId = res.services[0].uuid
			} else if (bleVersion * 1 === 2) {
				for (var i = 0; i < res.services.length; i++) {
					let t = res.services[i]
					if (t.uuid.indexOf('0000FFE0-0000-1000') > -1) {
						serviceId = t.uuid
					}
				}
			} else if (bleVersion * 1 === 3) {
				for (var i = 0; i < res.services.length; i++) {
					let t = res.services[i]
					if (t.uuid.indexOf('0000FF00-0000-1000') > -1) {
						serviceId = t.uuid
					}
				}
			}
			if (!serviceId) {
				uni.showToast({
					icon: 'error',
					title: '蓝牙连接失败'
				})
				return
			} else {
				console.log('serviceId', serviceId);
				getApp().globalData.bleObj.serviceId = serviceId
				getBLEDeviceCharacteristics(deviceId, serviceId, callback)
			}
		},
		fail: () => {
			if(callback){
				callback();
			}
			return
		}
	})
}


//连接蓝牙
function Connect(deviceId, callback) {
	var id = getApp().globalData.bleObj.deviceId;
	if (!deviceId) {
		deviceId = id
	}
	var state = getApp().globalData.bleObj.state;
	if (state && id != '') {
		Close(id);
	}
	uni.showLoading({
		title: '连接中',
		mask: false
	});
	getApp().globalData.bleObj.isNotify = false;
	uni.createBLEConnection({
		deviceId: deviceId,
		success: function(res) {
			console.log('createBLEConnection-success', res);
			if (res.errCode == 0 || res.errno == 0 || (res.errMsg&&res.errMsg.indexOf(':ok')>-1)) {
				//启用低功耗蓝牙设备特征值变化时的notify功能，订阅特征值
				setTimeout(function() {
					getBLEDeviceServices(deviceId, callback)
				}, 1000);
			} else {
				uni.hideLoading()
				if(callback){
					callback();
				}
				ErrorCode(res, '连接蓝牙success');
			}
		},
		fail: function(res) {
			uni.hideLoading()
			console.log('createBLEConnection-fail', res);
			if(callback){
				callback();
			}
			if (res.errCode == 10003) {
				uni.showToast({
					icon: 'none',
					title: '连接超时'
				})
				return
			}
			if (res.errCode == 10000) {
				Init(function() {
					Connect(deviceId);
				});
			} else {
				ErrorCode(res, '连接蓝牙fail');
			}
		}
	});
}

//断开连接
function Close(deviceId) {
	if (!deviceId) {
		deviceId = getApp().globalData.bleObj.deviceId
	}
	uni.closeBLEConnection({
		deviceId,
		success(res) {
			getApp().globalData.bleObj.state = false
			if (res.errCode == 0 || res.errno == 0) {

			} else {
				ErrorCode(res, '断开连接success');
			}
		},
		fail(res) {
			ErrorCode(res, '断开连接fail');
		}
	})
}

//搜索蓝牙
function SearchBluetooth(callback) {
	var language = uni.getStorageSync('language');
	uni.startBluetoothDevicesDiscovery({
		allowDuplicatesKey: false, //是否重复上报
		interval: 0, //上报设备的间隔。0 表示找到新设备立即上报，其他数值根据传入的间隔上报。
		success(res) {
			uni.onBluetoothDeviceFound(callback);
		},
		fail() {
			msg(language.b15);
		}
	})
}

//停止搜索蓝牙
function StopSeachBluetooth() {
	uni.stopBluetoothDevicesDiscovery({
		success(res) {
			console.log('蓝牙已停止搜索', res);
		}
	});
}

function BluetoothState() {
	uni.onBluetoothAdapterStateChange(function(res) {
		if (res) {
			if (!res.discovering) {
				msg('不支持蓝牙设备！');
			}
			if (res.available) {
				msg('正在搜索蓝牙！');
			}
		}
	});
}


export default {
	msg: msg,
	confirm: confirm,
	ErrorCode: ErrorCode,

	bleCallBack: bleCallBack,

	Init: Init,
	Connect: Connect,
	Close: Close,

	SearchBluetooth: SearchBluetooth,
	BluetoothState: BluetoothState,
	StopSeachBluetooth: StopSeachBluetooth,

}